package com.app.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.*;
import org.dom4j.io.*;
import org.dom4j.tree.DefaultElement;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import javax.servlet.http.HttpSession;
@SuppressWarnings({"unused","unchecked"})
public class StringUtil {

	private static String gbk = "GBK";
	@SuppressWarnings("unused")
	private static String gb2312 = "gb2312";
	private static String iso = "ISO-8859-1";
	private static String cp850 = "cp850";
	private static String cp936 = "cp936";
	private static String utf8 = "utf-8";
	private static String latin1 = "latin1";
	private static String latin2 = "latin2";
	
	public static String utf8togbk(String str){
		try {
			String ss = new String(str.getBytes(iso),utf8);			
			return ss;
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String getRandom(int num){
		 Random rnd = new Random();
         int[] nums = new int[25];
         for (int i=1; i<26; i++) {
                 int p = rnd.nextInt(25);
                 if (nums[p] != 0)
                         i--;
                 else
                         nums[p] = i;
         }
         String str = "";
         for (int i=0; i<num; i++) {
               str += nums[i] + "";
         }
		 return str;
	}
	
	public static String latin1togbk(String str) {
		try {
			str = new String(str.getBytes(utf8), gbk);
			return str;
		} catch (Exception ex) {
			ex.printStackTrace();
			return str;
		}
	}
	
	public static String latin1toutf8(String str) {
		try {
			return new String(str.getBytes(latin1), utf8);
		} catch (Exception ex) {
			return str;
		}
	}
	
	 /**
     * 返回字符串的拆分集合
     * @param String原始数据 String拆分标记
     * @return List
     */
	public static List splitStr(String strTarget, String strSplitor) {
		int i;
		if (strSplitor == null || strSplitor.equals("") || strTarget == null)
			return null;
		List al = new ArrayList();
		for (;;) {
			i = strTarget.indexOf(strSplitor);
			if (i > -1) {
				if (i == 0) {
					al.add("");
				} else {
					al.add(strTarget.substring(0, i));
				}
				strTarget = strTarget.substring(i + strSplitor.length());
			} else {
				al.add(strTarget);
				break;
			}
		}
		return al;
	}
	
	///将科学计数法转化成long
	public static long getLongData(double data){
		DecimalFormat   df   =   new   DecimalFormat("#");
		 String   ab   =   df.format(data);
		 return Long.parseLong(ab);
	}
	
	public static double getDoubleData(double data){
		DecimalFormat   df   =   new   DecimalFormat("#0.##");
		 String   ab   =   df.format(data);
		 return Double.parseDouble(ab);
	}
	
	public static double getBigDecimalData(double tempD2){
		BigDecimal big = new BigDecimal(tempD2);
		return (big.setScale(2, 0)).doubleValue();
	}
	
	public static String getNename(String name){
		if(name==null || name.equals("")){
			return "";
		}
		name = name.trim();
		String str = "";
		char[] s = name.trim().toCharArray();
		int num = 0;
		for(int i=0;i<s.length;i++){
			char ch = s[i];
			boolean   b   =   ( 'a'   <=   ch   &&   ch   <=   'z')   ||   ( 'A'   <=   ch   &&   ch   <=   'Z'); 
			if((num==0 || num==1) && b==true){
				str += ch;
				num = 1;
			}
			boolean bc =  ( '0'   <=   ch   &&   ch   <=   '9');
			if((num==1 || num==2) && bc==true){
				str += ch;
				num = 2;
			}
			if(num==2 && bc==false){
				break;
			}
		}
		return str;
	}
	
	/**
	 * 返回给定的字符串是否是数字<br>
	 * 0:不是数字; <Br>
	 * 1:整数;<br>
	 * 2:小数;<br>
	 * 3:小数位全为0;
	 * @param string
	 * @return
	 */
	 public static int isNumber2( String string ){
		 if(string==null || string.equals("")){
			return 0;
		}
	  int ll = string.length() ;
	  char firstChar = string.charAt(0);
	  int ddc = 0; int ddcc = 0;
	  if( firstChar=='-'||firstChar=='+'||firstChar=='.'||Character.isDigit(firstChar) ){
	   if( firstChar=='.' )ddc++;
	   for( int i=1 ; i<ll ; i++ ){
	    char c = string.charAt(i);
	    if( ddc>0 ) ddcc = c!='0'?ddcc+1:ddcc;
	    if( c=='.' ){ddc++; if( ddc>1 ) return 0;}
	    else if( !Character.isDigit( c ) ) return 0;
	    
	   }
	  }else return 0;
	  return ddc==0?1:(ddcc==0?3:2);
	 }
	
	public static String getSessionCityList(HttpSession session){
		List arealist = (List)session.getAttribute("AREALIST");
		String str = "(";
		String str2 = "";
		for(int i=0;i<arealist.size();i++){
			Map m = (Map)arealist.get(i);
			str2 += "'"+m.get("id").toString()+"',";
		}
		if(str2.length()>0) str2 = str2.substring(0, str2.length()-1);
		if(str2.length()>0) str += str2+")";
		else str += "'0')";
		return str;
	}
	
	public static double getDoubleTo2(String data){
		if(data==null) return 0d;
		else{
			try {
				java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");     
				String  aveprice = df.format(data); 
				double dd = Double.parseDouble(aveprice);
				return dd;
			} catch (Exception e) {
				return 0d;
			}
		} 
	}
	
	public static double getDoubleTo2(double data){
		if(data==0d) return 0d;
		else{
			try {
				java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");     
				String  aveprice = df.format(data); 
				double dd = Double.parseDouble(aveprice);
				return dd;
			} catch (Exception e) {
				return 0d;
			}
		} 
	}
	
	public static String utf8togbk2(String str){
		try {
			String ss = new String(str.getBytes(iso),utf8);			
			return ss;
		} catch (Exception e) {
			return "";
		}
	}
	/**
	 * uuid产生随机数
	 * @return String
	 */
	public static String createKey() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	public static String createKey2() {
		String sRand = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			// 取得一个随机字符
			String tmp = getRandomChar();
			sRand += tmp;
		}
		return sRand.toLowerCase();
	}
	
	public static String createKey3() {
		String sRand = "";
		Random random = new Random();
		for (int i = 0; i < 3; i++) {
			// 取得一个随机字符
			String tmp = getRandomChar();
			sRand += tmp;
		}
		return sRand.toLowerCase();
	}
	
	public static void main(String[] args){
		double d = 1.2162986201E10;
		System.out.println(StringUtil.getDoubleData(d));
	}
	
	public static int getRandomNum(){
		String num = (Math.random()*(9999-1000+1)+1000)+"";
		int num2 = Integer.parseInt(num.substring(0, num.indexOf(".")));
		return num2;
	}
	

	/***************************************************
	 * 生成随机字符的方法
	 * @return
	 */
	public static String getRandomChar() {
		int rand = (int) Math.round(Math.random() * 2);
		long itmp = 0;
		char ctmp = '\u0000';
		switch (rand) {
		case 1:
			itmp = Math.round(Math.random() * 25 + 65);
			ctmp = (char) itmp;
			return String.valueOf(ctmp);
		case 2:
			itmp = Math.round(Math.random() * 25 + 97);
			ctmp = (char) itmp;
			return String.valueOf(ctmp);
		default:
			itmp = Math.round(Math.random() * 9);
			return String.valueOf(itmp);
		}
	}

	/************************
	 * 字符转换
	 * @param str
	 * @return
	 */
	public static String iso2gbk(String str) {
		try {
			return new String(str.getBytes(iso), gbk);
		} catch (Exception ex) {
			return str;
		}
	}
	
	public static String gbk2iso(String str) {
		try {
			return new String(str.getBytes(gbk), iso);
		} catch (Exception ex) {
			return str;
		}
	}
	
	public static String iso2utf8(String str) {
		try {
			return new String(str.getBytes(iso), utf8);
		} catch (Exception ex) {
			return str;
		}
	}
	
	public static String cp850gbk(String str) {
		try {
			return new String(str.getBytes(cp850), gbk);
		} catch (Exception ex) {
			return str;
		}
	}

	public static String gbkcp850(String str) {
		try {
			return new String(str.getBytes(gbk), cp850);
		} catch (Exception ex) {
			return str;
		}
	}

	public static String gbkisocp850(String str) {
		try {
			String strStr = new String(str.getBytes(iso), gbk);
			return new String(strStr.getBytes(gbk), cp850);
		} catch (Exception e) {
			return str;
		}
	}

	public static String iso2cp850(String str) {
		try {
			return new String(str.getBytes(iso), cp850);
		} catch (Exception ex) {
			return str;
		}
	}

	public static String gbkcp936(String str) {
		try {
			return new String(str.getBytes(gbk), cp936);
		} catch (Exception ex) {
			return str;
		}
	}

	public static String cp936gbk(String str) {
		try {
			return new String(str.getBytes(cp936), gbk);
		} catch (Exception ex) {
			return str;
		}
	}

	public static String cp850cp936(String str) {
		try {
			return new String(str.getBytes(cp850), cp936);
		} catch (Exception ex) {
			return str;
		}
	}

	public static String cp936cp850(String str) {
		try {
			return new String(str.getBytes(cp936), cp850);
		} catch (Exception ex) {
			return str;
		}
	}
	
	

	/*******************************
	 * 例子 2123,3243,5465,65765
	 * @param l
	 * @return
	 */
	public static String getColumNames(List l) {
		String s = "";
		for (int i = 0; i < l.size(); i++) {
			String v = (String) l.get(i);
			s += v + ",";
		}
		s = s.substring(0, s.length() - 1);
		return s;
	}
	/*****************************
	 * 例子 'eee','6t56','5454gt'
	 * @param l
	 * @return
	 */
	public static String getColumNames3(List l) {
		String s = "";
		for (int i = 0; i < l.size(); i++) {
			String v = "'" + ((String) l.get(i)) + "'";
			s += v + ",";
		}
		s = s.substring(0, s.length() - 1);
		return s;
	}
	/*****************************
	 * 例子 a.name,a.age,a.bak
	 * @param l
	 * @return
	 */
	public static String getColumNames2(List l) {
		String s = "";
		for (int i = 0; i < l.size(); i++) {
			String v = "A." + (String) l.get(i);
			s += v + ",";
		}
		s = s.substring(0, s.length() - 1);
		return s;
	}


	/** 增加对获得的字符串为null的处理,将Null转化成"--" */
	public static String StringNoNull(String str) {
		String strString = "";
		if (("null".equals(str)) || ("".equals(str)) || (str == null)) {
			return strString;
		} else {
			return str;
		}
	}

	public static String null2space(String str) {
		return str == null ? "" : str;
	}

	public static String toWu(String str) {
		if (str == null || "".equals(str.trim()) || "null".equals(str.trim()))
			str = "无";
		return str;
	}

	/**
	 * 获得系统时间
	 * 
	 * @return
	 */
	public static String getSysTime() {

		String sysTime = "";
		Date now = new Date();
		DateFormat mediumDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		sysTime = mediumDateFormat.format(now);

		return sysTime;

	}

	/**
	 * 
	 * @param date
	 * @return yyyy-MM-dd
	 */
	public static String format(Date date) {
		try {
			return new SimpleDateFormat("yyyy-MM-dd").format(date);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 获取0到end之间的子串
	 * 
	 * @param str
	 * @param size
	 * @return
	 */
	public static String substr(String str, int end) {
		try {
			return str.substring(0, end);
		} catch (Exception e) {
			return str;
		}
	}
	
	
	 /**
     * 返回一个字符串的前几个字符表示
     * @param input String
     * @param count int
     * @return String
     */
    public static final String subString(String input, int count) {
        String result = "";
        if (input != null) {
            if (count < input.length()) {
                result = input.substring(0, count) + "...";
            } else {
                result = input;
            }
        }
        return result;
    }

    public static final String replaceAll(String str) {
        str = str.replaceAll("&", "&amp;");
        str = str.replaceAll("<", "&lt;");
        str = str.replaceAll(">", "&gt;");
        str = str.replaceAll("\r\n", "<BR>");
        str = str.replaceAll("\"", "&quot;");
        //str = str.replaceAll("'", "&sup1;");
        return str;
    }

    public static final String replaceForXml(String str) {
        if(str == null)
            return null;
        str = str.replaceAll("&", "&amp;");
        str = str.replaceAll("<", "&lt;");
        str = str.replaceAll(">", "&gt;");
        str = str.replaceAll("\r\n", "\\\\r\\\\n");
        str = str.replaceAll("\"", "&quot;");
        //str = str.replaceAll("'", "&sup1;");
        return str;
    }

    public static final String replaceSQL(String str) {
       str = str.replaceAll("%", "％");
      // str = str.replaceAll("_", "——");
       //str = str.replaceAll("\\", "＼");
       str = str.replaceAll("<", "&lt;");
       str = str.replaceAll(">", "&gt;");
       str = str.replaceAll("'", "’");
       str = str.replaceAll("\"", "“");
       return str;
   }


   public static final String replacePost(String str) {
       str = str.replaceAll("\"", "\\\"");
       return str;
   }


    public static final String replaceMore(String str) {
         str = str.replaceAll("&","&amp;");
        str = str.replaceAll("<", "&lt;");
        str = str.replaceAll(">", "&gt;");
        str = str.replaceAll("\r\n", "<BR>");
        str = str.replaceAll(" ", "&nbsp;");

        return str;
    }
    
    public static int nullto0(Integer n) {
    	if (n == null)
    		return 0;
    	else
    		return n;
    }
    public static double getNumberFormat(double data)
    {
    	return getNumberFormat(data,1);
    }
    public static double getNumberFormat(double data,int num){
    	double f1 = 0d;
    	try {
			BigDecimal b  =  new BigDecimal(data);   
			f1 = b.setScale(num,BigDecimal.ROUND_UP).doubleValue();
		} catch (RuntimeException e) {
			System.out.println(e.getMessage());
		}
	    return f1;
    }

    public static boolean isEmpty(String str){
    	if(null!=str&&!str.equalsIgnoreCase("")){
    		return false;
    	}
    	return true;
    }
    public static boolean isNumeric(String str){
    	if(isEmpty(str)){
    		return false;
    	}
		Pattern pattern = Pattern.compile("[0-9.]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	} 

	public static String parseTemplateIdToDate(String TemplateId,String Type){
		String str = "";
		if(null==TemplateId){
			return str;
		}
		if("YPG".equalsIgnoreCase(Type)){
			str = TemplateId.substring(TemplateId.lastIndexOf("E")+1,TemplateId.lastIndexOf("E")+9);
		}else if("JDMX".equalsIgnoreCase(Type)){
			str = TemplateId.substring(TemplateId.length()-14,TemplateId.length()-6);
		}else{
			str = TemplateId.substring(TemplateId.length()-8,TemplateId.length());
		}
		return str;
	}
	
	
}
